<template>
  <el-dialog :model-value="modelValue" @update:modelValue="onClose" :close-on-click-modal="false" :title="computedConfig.title" append-to-body width="1040px">
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="120px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="主体" prop="bizTypes">
            <FsSelect :key="refreshKey" v-model="formData.bizTypes" collapse-tags :initOptions="bizDeps" :request-method="busunessTypeList"
              multiple placeholder="请选择主体" @change="onBusinessTypeChange" style="width: 100%;"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属集团" prop="belongGroup">
            <el-input v-model="formData.belongGroup" placeholder="请输入所属集团" maxlength="50"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="关联单位" prop="orgNames">
            <FsSearchSelect :key="refreshKey" v-model="formData.orgNames" :initOptions="supplierList" :searchMethod="remoteSupplierList"
              @change="onSupplierChange" multiple placeholder="请选择关联单位" style="width: 100%;"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="关联项目编码" prop="projectCode">
            <el-input v-model="formData.projectCode" placeholder="请输入关联项目编码" maxlength="20"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="预计业务描述" prop="bizDescribe">
            <el-input v-model="formData.bizDescribe" placeholder="请输入预计业务描述" maxlength="200"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="公告数(元)" prop="noticeAmount">
            <el-input-number class="number-left" v-model="formData.noticeAmount" :controls="false" :precision="2" :max="1000000000000000" placeholder="请输入公告数" style="width: 100%;"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="归口部门" prop="belongDepartment">
            <el-cascader ref="cascaderRef" v-model="formData.belongDepartment" filterable :options="orgTreeData" :props="orgTreeProps" @change="onDepartmentChange" style="width: 100%;"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="关联交易类型" prop="relatedTransTypeName">
            <el-input v-model="formData.relatedTransTypeName" placeholder="请输入关联交易类型" maxlength="50"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="收/付款" prop="transType">
            <FsSelect v-model="formData.transType" :options="payReceiveOptions" placeholder="请选择收/付款" style="width: 100%;"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态" prop="enableStatus">
            <el-switch  v-model="formData.enableStatus" :active-valu="true" :inactive-value="false"/>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="onClose">取消</el-button>
        <el-button :loading="loading" type="primary" @click="onSubmit">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch, toRaw } from 'vue'
import api from '@/api/index'
import * as relatedApi from '@/api/Reimbursement/related-transaction.js'
import FsSearchSelect from '@/components/FsSearchSelect/index.vue'
import FsSelect from '@/components/FsSelect/index.vue'
import { remoteSupplierList, busunessTypeList } from '@/api/old-fssc'
import { payReceiveOptions } from '../config'
import { ElMessage } from 'element-plus'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  data: {
    type: Object,
    default: () => null
  }
})
const emits = defineEmits(['update:modelValue', 'success'])

const formRef = ref(null)
const formData = ref({})
const rules = ref({
  bizTypes: [
    { type: 'array', required: true, message: '请选择主体', trigger: 'change'}
  ],
  belongGroup: [
    { required: true, message: '请输入所属集团', trigger: 'change'}
  ],
  orgNames: [
    { type: 'array', required: true, message: '请选择关联单位', trigger: 'change'}
  ],
  projectCode: [
    { required: true, message: '请输入关联项目编码', trigger: 'change'}
  ],
  bizDescribe: [
    { required: true, message: '请输入预计业务描述', trigger: 'change'}
  ],
  noticeAmount: [
    { type: 'number', required: true, message: '请输入公告数', trigger: 'change'},
    { type: 'number', min: 0.01, message: '请输入大于0的公告数', trigger: 'change'},
  ],
  belongDepartment: [
    { required: true, message: '请选择归口部门', trigger: 'change'}
  ],
  relatedTransTypeName: [
    { required: true, message: '请输入关联交易类型', trigger: 'change'}
  ],
  transType: [
    { required: true, message: '请选择收/付款', trigger: 'change'}
  ],
})

const loading = ref(false)
const computedConfig = computed(() => {
  return {
    title: props.data.id ? '编辑' : '新增',
  }
})

const cascaderRef = ref()
const orgTreeData = ref([])
const orgTreeProps = ref({
  checkStrictly: true,
  multiple: false,
  emitPath: false,
  value: 'departmentId',
  label: 'departmentName'
})

let bizDeps = ref([])
const onBusinessTypeChange = ({value, selected}) => {
  bizDeps.value = toRaw(selected)
}

let supplierList = ref([])
const onSupplierChange = ({value, selected}) => {
  supplierList.value = toRaw(selected)
}

const onDepartmentChange  = (params1, params2, paramms3) => {

}

const initFormData = (id) => {
  if(id) {
    relatedApi.transactionProjectDetail(id).then((data) => {
      formData.value = {
        id: data.id,
        relatedTransConfigId: props.data.relatedTransConfigId,
        bizTypes: data.bizDeps.map((item) => item.bizDepCode),
        belongGroup: data.belongGroup,
        orgNames: data.orgList.map((item) => item.orgName),
        projectCode: data.projectCode,
        bizDescribe: data.bizDescribe,
        noticeAmount: data.noticeAmount,
        belongDepartment: data.belongDepartment,
        relatedTransTypeName: data.relatedTransTypeName,
        transType: data.transType,
        enableStatus: data.enableStatus,
        usedAmount: data.usedAmount,
        remainingAmount: data.remainingAmount,
      }
      bizDeps.value = data.bizDeps.map((item) => { return {
        value: item.bizDepCode, label: item.bizDepName
      }})
      supplierList.value = data.orgList.map((item) => { return {
        type: item.type,
        code: item.orgCode,
        name: item.orgName,
        value: item.orgName,
        label: item.orgName
      }})
      refreshKey.value++
    })
  } else {
    formData.value = {
      relatedTransConfigId: props.data.relatedTransConfigId,
      id: '',
      bizTypes: [],
      belongGroup: '',
      orgNames: [],
      projectCode: '',
      bizDescribe: '',
      noticeAmount: undefined,
      belongDepartment: '',
      relatedTransTypeName: '',
      transType: '',
      enableStatus: true,
      usedAmount: undefined,
      remainingAmount: undefined,
    }
    bizDeps.value = []
    supplierList.value = []
    refreshKey.value++

    setTimeout(() => {
      if (formRef.value) {
        formRef.value.clearValidate()
      }
    }, 0);
  }
}

const onClose = () => {
  bizDeps.value = []
  supplierList.value = []
  emits('update:modelValue', false)
}

const onSubmit = () => {
  loading.value = true
  formRef.value.validate().then(() => {
    let method = formData.value.id ? relatedApi.transactionProjectEdit : relatedApi.transactionProjectAdd
    let checkNodes = cascaderRef.value.getCheckedNodes()
    let submitData = {
      relatedTransConfigId: formData.value.relatedTransConfigId,
      id: formData.value.id,
      bizDeps: bizDeps.value.map((item) => {
        return {
          bizDepCode: item.value,
          bizDepName: item.label
        }
      }),
      belongGroup: formData.value.belongGroup,
      orgList: supplierList.value.map((item) => {
        return {
          type: item.type,
          orgCode: item.code,
          orgName: item.name
        }
      }),
      projectCode: formData.value.projectCode,
      bizDescribe: formData.value.bizDescribe,
      noticeAmount: formData.value.noticeAmount,
      belongDepartment: formData.value.belongDepartment,
      belongDepartmentName: checkNodes[0].data.label,
      relatedTransTypeName: formData.value.relatedTransTypeName,
      transType: formData.value.transType,
      enableStatus: formData.value.enableStatus,
      usedAmount: formData.value.usedAmount,
      remainingAmount: formData.value.remainingAmount,
    }

    console.log(submitData.noticeAmount.toString())

    method(submitData).then(() => {
      ElMessage.success('操作成功')
      emits('success')
      onClose()
    }).finally(() => {
      loading.value = false
    })
  }).finally(() => {
    loading.value = false
  })
}

const refreshKey = ref(1)
watch(() => props.data, (val) => {
  initFormData(val.id)
}, { immediate: true })
api.publicApi.orgInfo().then((data) => {
  orgTreeData.value = data
})

</script>

<style lang="scss" scoped>
.dialog-footer {
  text-align: right;
}
// 数字输入框居左
.number-left {
  :deep(.el-input__inner) {
    text-align: left;
  }
}
</style>
